package cn.tedu.boot62.controller;

import cn.tedu.boot62.entity.User;
import cn.tedu.boot62.entity.Weibo;
import cn.tedu.boot62.mapper.WeiboMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
public class WeiboController {
    @Autowired(required = false)
    WeiboMapper mapper;

    @RequestMapping("/send")
    public int send(Weibo weibo, MultipartFile pic, HttpSession session) throws IOException {
        //得到会话对象中 曾经登录的用户对象
        User user = (User) session.getAttribute("user");
        if (user==null){
            return 0;//没有登录过
        }

        //得到原始文件名
        String fileName = pic.getOriginalFilename();
        //得到后缀名
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //得到唯一文件名
        fileName = UUID.randomUUID()+suffix;
        //保存图片的路径
        String dirPath = "d:/upload";
        File dirFile = new File(dirPath);
        //判断如果文件夹不存在 创建
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        //得到文件的完整路径
        String filePath = dirPath+"/"+fileName;
        //保存文件  异常抛出
        pic.transferTo(new File(filePath));
        //把图片的相对路径(图片名)添加到weibo对象中
        weibo.setUrl(fileName);
        //把作者名 和用户的id保存到weibo对象中
        weibo.setAuthor(user.getNick());
        weibo.setUserId(user.getId());

        //把weibo对象中的所有数据 保存到weibo表里面
        mapper.insert(weibo);
        return 1;//代表发布成功!
    }
    @RequestMapping("/select")
    public List<Weibo> select(){
        return mapper.select();
    }
    @RequestMapping("/selectmyweibo")
    public List<Weibo> selectMyWeibo(HttpSession session){
        //得到当前登录的用户对象
        User user = (User) session.getAttribute("user");

        return mapper.selectMyWeibo(user);
    }

    @RequestMapping("/delete")
    public void delete(int id){
        mapper.delete(id);
    }
}
